﻿using NHibernate;
using DomainModel.Abstract;
using DomainModel.Entities;
using System.Collections.Generic;
using NHibernate.Criterion;

namespace DomainModel.Concrete
{
    public class NewsRepository : RepositoryBase, INewsRepository
    {

        public IEnumerable<News> GetAll()
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(News)).AddOrder(Order.Desc("NewsID"));
                return criteria.List<News>();
            }
        }


        public IEnumerable<News> GetAll(bool isPublished)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(News));
                criteria.Add(Expression.Eq("IsPublished", isPublished)).AddOrder(Order.Desc("NewsID"));
                return criteria.List<News>();
            }
        }


        public IEnumerable<News> GetTop(int topNumber)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                ICriteria criteria = session.CreateCriteria(typeof(News)).SetMaxResults(topNumber).AddOrder(Order.Desc("NewsID"));
                return criteria.List<News>();
            }
        }


        public News Get(int? id)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                return session.Get<News>(id);
            }
        }

        public void Save(News news)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                session.SaveOrUpdate(news);
                session.Flush();
            }
        }

        public void Delete(int id)
        {
            using (ISession session = SessionFactory.OpenSession())
            {
                session.Delete(Get(id));
                session.Flush();
            }
        }

    }
}
